package com.ruicar.afs.cloud.admin.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.admin.entity.SysDictData;
import com.ruicar.afs.cloud.admin.mapper.SysDictDataMapper;
import com.ruicar.afs.cloud.admin.service.SysDictDataService;
import com.ruicar.afs.cloud.admin.service.SysDictService;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.util.TenantUtil;
import com.ruicar.afs.cloud.common.datasync.componts.SyncHelper;
import com.ruicar.afs.cloud.components.datadicsync.constants.Constants;
import com.ruicar.afs.cloud.components.datadicsync.dto.DicDataDto;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * The type SysDictDataServiceImpl.
 * <p>
 * Created on 2019-02-20
 *
 * @author Fzero
 */
@Service
@AllArgsConstructor
@Slf4j
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictData> implements SysDictDataService, ApplicationListener<ApplicationReadyEvent> {
    private final SysDictService dictService;
    private final Environment environment;
    private static boolean dicDataPublish = false;
    @Override
    public void publishDicDataToSync() {
        if(!dicDataPublish){
            return;
        }
        new Thread(() -> {
            try {
                Map<String, List<DicDataDto>> dicMap = new HashMap<>();
                TenantUtil.close();
                dictService.list().forEach(dict -> {
                    dicMap.put(
                            dict.getType(),
                            this.baseMapper
                                    .selectList(Wrappers.<SysDictData>lambdaQuery().eq(SysDictData::getDictId, dict.getId()).eq(SysDictData::getStatus, CommonConstants.COMMON_YES).orderByAsc(SysDictData::getSortOrder))
                                    .stream().map(dicData -> {
                                DicDataDto dicDto = new DicDataDto();
                                dicDto.setTitle(dicData.getTitle());
                                dicDto.setValue(dicData.getValue());
                                return dicDto;
                            }).collect(Collectors.toList())
                    );
                });
                JSONObject object = new JSONObject();
                object.put(Constants.DIC_KEYS.getKey(), dicMap);
                SyncHelper.publishParams(Constants.DIC_KEYS, object);
            }catch (Exception e){
                log.error("数据字典同步失败",e);
            }finally {
                TenantUtil.open();
            }
        }).start();
    }
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        dicDataPublish = environment.getProperty("com.ruicar.afs.cloud.dicpublish",Boolean.class,Boolean.FALSE);
        this.publishDicDataToSync();
    }
}
